package org.jeecg.modules.purchase.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.bid.entity.Bid;
import org.jeecg.modules.bid.entity.BidManagement;
import org.jeecg.modules.bid.service.IBidManagementService;
import org.jeecg.modules.bid.service.IBidService;
import org.jeecg.modules.bid.vo.BidManagementVO;
import org.jeecg.modules.file.entity.ProcurementFile;
import org.jeecg.modules.file.service.IProcurementFileService;
import org.jeecg.modules.purchase.Vo.PurchaseRecordException;
import org.jeecg.modules.purchase.Vo.BidSupplierinfoQuery;
import org.jeecg.modules.purchase.Vo.PurchaseRecordVo;
import org.jeecg.modules.purchase.dto.PurchaseRecordRequest;
import org.jeecg.modules.purchase.service.IPurchasePlanService;
import org.jeecg.modules.supplier.service.ISupplierService;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Api(tags = "采购记录管理44")
@RestController
@RequestMapping("/procurement/purchaseRecord")
@Slf4j
public class PurchaseRecordController {

    @Resource
    private IPurchasePlanService purchasePlanService;

    @Resource
    private IBidManagementService bidManagementService;

    @Resource
    private IBidService bidService;

    @Resource
    private IProcurementFileService procurementFileService;

    @Resource
    private ISupplierService supplierService;

    @AutoLog(value = "采购记录管理-分页列表查询")
    @ApiOperation(value = "采购记录管理-分页列表查询", notes = "采购记录管理-分页列表查询+模糊查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(PurchaseRecordRequest purchaseRecordRequest) {
        Integer pageNum = purchaseRecordRequest.getPageNum();
        Integer pageSize = purchaseRecordRequest.getPageSize();
        Page<BidManagement> page = new Page<>(pageNum, pageSize);
        QueryWrapper<BidManagement> queryWrapper = new QueryWrapper<>();
        // 状态模糊查询
        if (purchaseRecordRequest.getPublishedStatus() != null && !purchaseRecordRequest.getPublishedStatus().trim().isEmpty()) {
            queryWrapper.eq("published_status", purchaseRecordRequest.getPublishedStatus().trim());
        }
        // 项目名称模糊查询
        if (purchaseRecordRequest.getProjectName() != null && !purchaseRecordRequest.getProjectName().trim().isEmpty()) {
            queryWrapper.like("project_name", purchaseRecordRequest.getProjectName().trim());
        }
        // 项目编号模糊查询
        if (purchaseRecordRequest.getProjectNumber() != null && !purchaseRecordRequest.getProjectNumber().trim().isEmpty()) {
            queryWrapper.like("project_number", purchaseRecordRequest.getProjectNumber().trim());
        }
        // 采购查询起止时间
        if (purchaseRecordRequest.getStartTime() != null && purchaseRecordRequest.getEndTime() != null ) {
            queryWrapper.gt("plan_purchase_time", purchaseRecordRequest.getStartTime())
                    .lt("plan_purchase_time", purchaseRecordRequest.getEndTime());
        }
        try {
            Page<BidManagement> purchasePageList = bidManagementService.page(page, queryWrapper);
            List<BidManagementVO> purchaseRecordVoList = purchasePageList.getRecords().stream()
                    .map(plan -> {
                        BidManagementVO vo = new BidManagementVO();
                        // 进行属性拷贝和转换
                        BeanUtils.copyProperties(plan, vo);
                        if(vo.getPublishedStatus() != null && vo.getPublishedStatus().equals("6")){
                            BidManagementVO bidManagement =bidManagementService.getBidManagementByPurchaseId(vo.getId());
                            vo.setWinningName(bidManagement.getWinningName());
                            vo.setBidPrice(bidManagement.getBidPrice());
                        }
                        return vo;
                    }).collect(Collectors.toList());
            return Result.OK(purchaseRecordVoList);
        } catch (Exception e) {
            log.error("查询采购记录列表失败：{}", e.getMessage());
            return Result.error("查询采购记录列表失败");
        }
    }

    @AutoLog(value = "采购记录管理-根据采购项目ID获取详细信息")
    @ApiOperation(value = "采购记录管理-根据采购项目ID获取详细信息", notes = "采购记录管理-根据采购项目ID获取详细信息(查看功能的上下表)")
    @GetMapping(value = "/getPurchaseRecordById")
    public Result<?> getPurchaseRecordById(String purchaseId) {
        try {
            BidManagementVO bidManagementVO = bidManagementService.getBidManagementByPurchaseId(purchaseId);
            PurchaseRecordVo purchaseRecordVo = new PurchaseRecordVo();
            BeanUtils.copyProperties(bidManagementVO,purchaseRecordVo);
            List<ProcurementFile> file = procurementFileService.getFilesByBiz(purchaseId,"purchase");
            purchaseRecordVo.setProcurementFile(file);
            String remark = purchasePlanService.getById(purchaseId).getRemark();
            purchaseRecordVo.setRemark(remark);
            return Result.OK(purchaseRecordVo);
        }catch (Exception e){
            log.error("查询采购记录详细失败：{}", e.getMessage());
            return Result.error("查询采购记录详细失败");
        }
    }


    @AutoLog(value = "采购记录管理-按采购项目ID查询各供应商投标信息")
    @ApiOperation(value = "采购记录管理-按采购项目ID查询各供应商投标信息", notes = "按采购项目ID查询各供应商投标信息（查看的中表和公示下表可用）")
    @GetMapping(value = "/bidInfoByPurchaseId")
    public Result<?> bidInfoListByPurchaseId(String purchaseId) {
        List<Bid> bidListAsPurchase = bidService.list(new QueryWrapper<Bid>().eq("purchase_id", purchaseId));
        // 映射到BidSupplierinfoQuery
        List<BidSupplierinfoQuery> bidInfoListByPurchaseId = bidListAsPurchase.stream()
                .map(bid -> {
                    BidSupplierinfoQuery bidSupplierinfoQuery = new BidSupplierinfoQuery();
                    BeanUtils.copyProperties(bid, bidSupplierinfoQuery);
                    String creditCode = supplierService.getCreditCodeBySupplierId(bid.getSupplierId());
                    bidSupplierinfoQuery.setCreditCode(creditCode);
                    return bidSupplierinfoQuery;
                })
                .sorted(Comparator.comparing(BidSupplierinfoQuery::getIsWinning, Comparator.reverseOrder()))
                .collect(Collectors.toList());
                return Result.OK(bidInfoListByPurchaseId);
    }

    @AutoLog(value = "采购记录管理-设置异常信息")
    @ApiOperation(value = "采购记录管理-设置异常信息", notes = "采购记录管理-设置异常信息")
    @PostMapping(value = "/setException")
    public Result<?> setException(@RequestBody PurchaseRecordException purchaseRecordException) {
        String id = purchaseRecordException.getPurchaseId();
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
       BidManagement bidManagement = bidManagementService.getById(id);
        bidManagement.setPublishedStatus(purchaseRecordException.getPublishedStatus());
        bidManagement.setExceptionStatusReason(purchaseRecordException.getExceptionStatusReason());
        bidManagement.setExceptionStatusRemark(purchaseRecordException.getExceptionStatusRemark());
        bidManagement.setUpdateBy(sysUser.getUsername());
        bidManagement.setUpdateTime(new Date());
       return bidManagementService.updateById(bidManagement) ? Result.OK("设置异常信息成功") : Result.error("设置异常信息失败");
    }


}
